import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

import { useUserStore } from '@/store';
import { router } from '@/router';

NProgress.configure({ showSpinner: false });

const whiteListRouters = ['/login'];

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	const userStore = useUserStore();

	const { token } = userStore;

	if (token) {
		if (to.path === '/login') {
			next();
			return;
		} else {
			next();
		}
	} else {
		/* white list router */
		if (whiteListRouters.indexOf(to.path) !== -1) {
			next();
		} else {
			next({
				path: '/login',
				query: { redirect: encodeURIComponent(to.fullPath) },
			});
		}
		NProgress.done();
	}
});

router.afterEach(() => {
	NProgress.done();
});
